package com.ccteam.shared.domain.auth

import cn.hutool.crypto.asymmetric.KeyType
import cn.hutool.crypto.asymmetric.RSA
import com.ccteam.model.Resource
import com.ccteam.network.ApiError
import com.ccteam.network.ApiResult
import com.ccteam.shared.data.auth.AuthRepository
import com.ccteam.shared.domain.SuspendUseCase
import com.orhanobut.logger.Logger
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/18
 *
 * 获取RSA密钥Domain层，
 * 传入[String] 密码
 * 返回[String] 通过RSA加密后的密码数据
 */
class RSADataUseCase @Inject constructor(
    private val authRepository: AuthRepository
): SuspendUseCase<String, String>(
    Dispatchers.IO
){
    override suspend fun execute(parameters: String): Resource<String> {
        return when (val result = authRepository.getRsaPublicKey()) {
            is ApiResult.Success -> {
                return if(!result.data.data.isNullOrEmpty()){
                    Logger.d("密钥获取成功:${result.data.data!!}")
                    val rsa = RSA(null,result.data.data)
                    val rsaPassword = rsa.encryptBcd(parameters, KeyType.PublicKey)

                    Logger.d("密码加密:$rsaPassword")
                    Resource.Success(rsaPassword)
                } else {
                    Resource.Error(ApiError.serverErrorCode,"密钥为空，请稍后再试")
                }
            }
            is ApiResult.Failure -> {
                Resource.Error(ApiError.serverErrorCode,result.errorMsg)
            }
            else -> {
                Resource.Error(ApiError.serverErrorCode,"未知错误")
            }
        }
    }
}